package com.healthdata.config;

import com.healthdata.util.ResponseUtil;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.AuthenticationCredentialsNotFoundException;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler({AuthenticationCredentialsNotFoundException.class, BadCredentialsException.class})
    public void handleAuthenticationException(HttpServletResponse response) throws IOException {
        ResponseUtil.sendErrorResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "认证失败，请提供有效的凭证");
    }

    @ExceptionHandler(AccessDeniedException.class)
    public void handleAccessDeniedException(HttpServletResponse response) throws IOException {
        ResponseUtil.sendErrorResponse(response, HttpServletResponse.SC_FORBIDDEN, "权限不足，无法访问该资源");
    }
}